package com.yuncheng.oaApi.controller;


import com.yuncheng.oaApi.vo.OaFlowVo;
import com.yuncheng.oaApi.vo.OaFwVo;
import com.yuncheng.oaApi.vo.OaReturnVo;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.busService.MyLcFlowService;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.oaApi.constant.OafwOaFlowConstants;
import com.yuncheng.oaApi.constant.OaswOaFlowConstants;
import com.yuncheng.oaApi.entity.OaFw;
import com.yuncheng.oaApi.entity.OaJobEntity;
import com.yuncheng.oaApi.lcService.OaFwOaFlowService;
import com.yuncheng.oaApi.mapper.OaFwFlowMapper;
import com.yuncheng.oaApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Api(tags = "OA-发文")
@RestController
@RequestMapping("/api/spzx-oa/flow-fw")
public class OaFwFlowController {
    private static final Logger log = LoggerFactory.getLogger(OaFwFlowController.class);
    @Resource
    private OafwOaFlowConstants oafwFlowConstant;

    @Resource
    private OaFwFlowMapper oaFwFlowMapper;

    @Resource
    private OaFwOaFlowService oaFwFlowService;

    @Resource
    private IOaFwService oaFwService;

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private MyLcFlowService myLcFlowService;

    @Resource
    @Lazy
    private IOaSysTzMessageService sysTzMessageService;

    /**
     * 流程列表分页查询
     *
     * @param oaFwVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            OaFwVo oaFwVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser) {
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaFwVo> page = new Page<>(pageNo, pageSize);
        oaFwVo.setFlcmc(oafwFlowConstant.getFlowName());
        IPage<OaFwVo> list = oaFwFlowMapper.flowJkPage(page, onlyCurrentUser, user, oaFwVo);
        return HttpResult.ok(list);
    }

    /**
     * 我的已办
     */
    @AutoLog(value = "流程列表-我的已办")
    @ApiOperation(value = "流程列表-我的已办")
    @GetMapping("myJobPage")
    public HttpResult<?> myJobPage(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaFwVo oaFwVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaFwVo> page = new Page<>(pageNo, pageSize);
        IPage<OaFwVo> list = oaFwFlowMapper.myYbFlowPage(page, true, user, oaFwVo);
        return HttpResult.ok(list);
    }

    @AutoLog(value = "发起发文流程")
    @ApiOperation(value = "发起发文流程")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody OaFw oaFw) {
        String oaid = "";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        if (StringUtils.isNotBlank(oaFw.getId())) {
            OaFw oaids = oaFwService.getById(oaFw.getId());
            ConvertUtils.register(new DateConvert(), java.util.Date.class);
            try {
                BeanUtils.populate(oaids, BeanUtils.describe(oaFw));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}", e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}", e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法", e.getMessage());
            }
            oaid = oaFw.getId();
            oaFwService.updateById(oaids);
        } else {
            oaid = GetUuIdUtils.ReplaceUuId();
            oaFw.setId(oaid);

            oaFw.setFuserid(currentUser.getId());
            oaFwService.save(oaFw);
        }
        /**
         * @Author: lhb
         * @Description : 是否发起流程   如果是开始申请就跳转流程
         *               在这里设置 nextNodeName 指定下个环节节点 做当前跳转流程的判断，然后设置变量接收环节的值，写到nextNodeName中
         * @DateTime:
         * @Params: Fsffqlc
         */
        String msg = "保存成功";
        // 初始化流程
        Result result = oaFwFlowService.initJob(oaid, currentUser);
        if (!result.isSuccess()) {
            return HttpResult.error(result.getMessage());
        } else {
            OaJobEntity job = (OaJobEntity) result.getResult();
            if (job != null) {
                // 是否提交流程
                if (StringUtils.isBlank(oaid)) {
                    return HttpResult.error("参数丢失");
                }
                String flczt = oaFw.getFlczt();
                if (StringUtils.isBlank(flczt)) {
                    oaFw.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
                }
                if (StringUtils.isNotBlank(oaFw.getFsffqlc()) && oaFw.getFsffqlc().equals("是")) {
                    Result result1 = oaFwFlowService.passJob(oaid, job.getId(), "同意", "", "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    sysTzMessageService.tjMessage(oaid);
                    myLcFlowService.recall(oaid);
                    msg = "提交成功";
                }
            }
        }
        HttpResult http = new HttpResult(true);
        http.setMessage(msg);
        http.setResult(oaFw);
        return http;
    }

    /**
     * 发文保存接口
     */
    @AutoLog(value = "发文保存接口")
    @ApiOperation(value = "发文保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存

        String jobId = oaFlowVo.getJobid(); // 当前流程任务id
        String oaid = oaFlowVo.getOaid(); // 当前办公主键id
        String opinion = oaFlowVo.getOpinion(); // 办理意见

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        // 流程处理
        Result httpResult = oaFwFlowService.handleFlow(oaFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()) {
            return HttpResult.error(httpResult.getMessage());
        }
        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        res.setResult(map);
        return res;
    }

    /**
     * 收文提交接口
     */
    @AutoLog(value = "收文提交接口")
    @ApiOperation(value = "收文提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = oaFlowVo.getJobid();
        String oaid = oaFlowVo.getOaid();
        String opinion = oaFlowVo.getOpinion();
        OaFw oaId = oaFwService.getById(oaid);
        OaJobEntity job = spcySqsxJobService.getById(jobId);

        if (job.getFhjmc().equals(OaswOaFlowConstants.HJMC_GT)) {

        } else {
            oaId.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
        }
        if (StringUtils.isBlank(oaId.getFsffqlc())) {
            oaId.setFsffqlc("是");
        }


        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/
        oaFwService.updateById(oaId);
        OaJobEntity nowJob = null;
        Result httpResult1 = oaFwFlowService.handleFlow(oaFlowVo, nowJob, jobId, oaid, submitType, opinion);

        if (!httpResult1.isSuccess()) {
            return HttpResult.error(httpResult1.getMessage());
        }
        sysTzMessageService.tjMessage(oaid);
        myLcFlowService.recall(oaid);
        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid", name = "流程任务id", required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid") String jobid) {
        if (StringUtils.isBlank(jobid)) {
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = oaFwFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }

    /**
     * 获取已办列表-通过当前流程id-自定义退回
     *
     * @param jobid
     * @return
     */
    @AutoLog(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiOperation(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj", value = "是否指定环节，默认：true，指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid", defaultValue = "") String jobid,
                                       @RequestParam(value = "isZdhj", defaultValue = "true") boolean isZdhj) {
        List<Map<String, String>> currentJobPrevious = oaFwFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }

    /**
     * 退回环节
     *
     * @return
     */
    @AutoLog(value = "自定义-退回环节")
    @ApiOperation(value = "自定义-退回环节")
    @PostMapping(value = "returnUpperzdyFlowJob")
    public HttpResult<?> returnUpperzdyFlowJob(@RequestBody OaReturnVo oaReturnVo) {
        oaFwFlowService.returnZdJob(oaReturnVo);
        return HttpResult.ok("退回成功");
    }
    /**
     * 退回上一环节流程任务
     */
    @AutoLog(value = "退回上一环节流程任务")
    @ApiOperation(value = "退回上一环节流程任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id", required = true),
            @ApiImplicitParam(name = "opinion", value = "意见", required = true)
    })
    @PostMapping(value = "returnUpperFlowJob")
    public HttpResult<?> returnUpperFlowJob(@RequestBody Map map) {

        String jobid = map.get("jobid").toString();
        String opinion = map.get("opinion").toString();
        Result result = oaFwFlowService.getReturnUpperFlowJob(jobid, opinion);
        if (!result.isSuccess()) {
            return HttpResult.error(result.getMessage());
        }

        return HttpResult.ok("退回成功");
    }

    @AutoLog(value = "删除收文流程")
    @ApiOperation(value = "删除收文流程")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids", value = "流程任务id,逗号分割", required = true)
    })
    @DeleteMapping(value = "deleteLgqsFlowJob")
    public HttpResult<?> deleteLgqsFlowJob(@RequestParam(value = "jobids") String jobids) {
        if (StringUtils.isBlank(jobids)) {
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)) {
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)) {
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    OaFw oaFw = oaFwService.getById(job.getFpid());
                    if (oaFw != null) {
                        oaFwService.removeById(job.getFpid());

                        logNr = "删除收文流程" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(oaFw);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaLogConstant.LOGS_OA_SW, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }
        return HttpResult.ok("删除成功");
    }


}
